﻿

//关闭弹出层
function closeWindow(data) {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.data = data;
    parent.layer.close(index);
}

jQuery.extend({
    download: function (url, data, method) {
        if (url && data) {
            method = method || 'post';
            data = typeof (data) == "string" ? data : decodeURIComponent($.myParam(data));
            var inputs = '';
            var submitJson = {};
            $.each(data.split('&'), function () {
                var pair = this.split('=');
                inputs += '<input type="hidden"   name="{0}" value="{1}"/>'.format(pair[0], pair[1]);
                submitJson[pair[0]] = pair[1];
            });
            if(method.toLocaleLowerCase() == 'get'){
            	var objForm = $("#fileForm");
	            if (objForm.length == 0) {
	                objForm = $('<form id="fileForm" method="{0}" target="fileIFrame" action="{1}">{2}</form><iframe id="fileIFrame" name="fileIFrame" style="display:none;"></iframe>'.format(method, url, inputs)).appendTo('body');
	            } else {
	                objForm.attr("method", method).attr("action", url).html(inputs);
	            }
	            objForm.submit();
	            return false;
            }
            layer.msg('玩命下载中……', {icon: 16, shade: 0.5, time:0, maxWidth:200});
            $.ajax({
            	type: "post",
            	url: url,
            	data: submitJson,
            	success: function(d){
            		layer.closeAll('dialog');
//          		console.log(d,"    ",d.substring(d.indexOf('upfile')).replace(/\\/g,'/'));
					$('#downloadTableUrl').remove();
					$('body').append('<iframe id="downloadTableUrl" style="display:none;" src="/'+ d.substring(d.indexOf('upfile')).replace(/\\/g,'/') +'"></iframe>');	
            	},
            	error: function(msg){
            		layer.closeAll('dialog');
            		swal('下载出错','','error');
            		console.log('msg',msg);
            	},
            });
        }
    },
    isJson: function (obj) {
        var isjson = typeof (obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
        return isjson;
    },
    myParam: function (a, traditional) {
        var prefix, s = [], rbracket = /\[\]$/,
            add = function (key, value) {
                value = jQuery.isFunction(value) ? value() : (value == null ? "" : value);
                s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
            },
        buildParams = function (prefix, obj, traditional, add) {
            var name;
            if (jQuery.isArray(obj)) {
                jQuery.each(obj, function (i, v) {
                    if (traditional || rbracket.test(prefix)) {
                        add(prefix, v);
                    } else {
                        // Item is non-scalar (array or object), encode its numeric index.
                        buildParams(prefix + "[" + (typeof v === "object" ? i : "") + "]", v, traditional, add);
                    }
                });

            } else if (!traditional && jQuery.type(obj) === "object") {
                // Serialize object item.
                for (name in obj) {
                    buildParams(prefix + "[" + name + "]", obj[name], traditional, add);
                }

            } else {
                // Serialize scalar item.
                add(prefix, obj);
            }
        };

        if (traditional === undefined) {
            traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
        }

        if (jQuery.isArray(a) || (a.jquery && !jQuery.isPlainObject(a))) {
            // Serialize the form elements
            jQuery.each(a, function () {
                add(this.name, this.value);
            });

        } else {
            for (prefix in a) {
                buildParams(prefix, a[prefix], traditional, add);
            }
        }

        // Return the resulting serialization
        return s.join("&");
    },

    /*
    * 功能：    生成guid
    * 参数：    无
    * 返回值：  guid
    * 创建时间：2016-01-25
    */
    UUID: function () {
        var s = [], itoh = '0123456789ABCDEF'.split('');
        for (var i = 0; i < 36; i++) s[i] = Math.floor(Math.random() * 0x10);
        s[14] = 4;
        s[19] = (s[19] & 0x3) | 0x8;
        for (var i = 0; i < 36; i++) s[i] = itoh[s[i]];
        s[8] = s[13] = s[18] = s[23] = '-';
        return s.join('');
    },

    /*
    * 功能：    获取url参数值
    * 参数：    url 地址
    * 返回值：  参数键值对
    * 创建时间：2016-01-26
    */
    getUrlParms: function (url) {
        var paramsArray = {};
        var fisrtIndex = url.indexOf("?");
        if (fisrtIndex + 1 < url.length) {
            var tmparray = url.substring(fisrtIndex + 1).split("&");
            var reg = /[=|^==]/;
            if (tmparray != null) {
                for (var i = 0; i < tmparray.length; i++) {
                    var set1 = tmparray[i].replace(reg, '&');
                    var tmpStr2 = set1.split('&');
                    paramsArray[tmpStr2[0]] = unescape(tmpStr2[1]);
                }
            }
        }
        // 将参数数组进行返回
        return paramsArray;
    },

    /*
    * 功能：    导出数据到EXCEL下载
    * 参数：    options：参数  格式如下
                {
                   columnInfoList:[{
                            "Align": "left", /取值 left right center
                            "Header": "标题头",
                            "Field": "绑定域"  //绑定字段名称
                        }]
                   "api":取数接口地址,  如果该参数有值则会进行后台取数  
                   condition":后台取数查询参数
                   "data": 前台传给后台的数据，
                   "type":get 还是post 默认post
                   fileName:导出文件名
                }
    * 返回值：  无
    * 创建时间：2016-02-22
    */
    ExportXLS: function (fileName, type) {
            if ($("#excelForm").length == 0) {
                $('<form id="excelForm"  method="post" target="excelIFrame"><input type="hidden" name="excelParam" id="excelData" /></form><iframe id="excelIFrame" name="excelIFrame" style="display:none;"></iframe>').appendTo("body");
                var param = { "FileName": fileName, "Type": type, action: "ExportExcel" };
            //导出数据
            $("#excelData").val(JSON.stringify(param));
            var excelForm = document.getElementById("excelForm");
            excelForm.action = "../Excel/PostHandler.ashx";
            excelForm.submit();
        }
    },
    /*
    * 功能：    根据业务类型下载导入数据得模版文件
    * 参数：    type：业务类型 取值参照 DownLoadHandler 枚举
    * 返回值：  无
    * 创建时间：2016-08-19
    */
    DownloadExcelTemplate: function (type) {
        if (type == "undefined") {
            return;
        }
        var param = { filetype: type, action: "DownLoadTemplate" };
        //调用api方法
        $.download("../Excel/GetHandler.ashx", param, "get");
    },

    ImportExcelData: function (type) {
        if (type == "undefined") {
            return;
        }
        var UserID = JSON.parse(window.sessionStorage.getItem('login-info'));
        if(!Y.checkNull(UserID))
        	UserID = UserID.UserId;
        var param = { filetype: type, action: "ImportTemplate", UserID: UserID };
        //调用api方法
        $.download("../Excel/PostHandler.ashx", param, "post");
    },
    /*
* 功能：    导出数据到EXCEL下载
* 参数：    options：参数  格式如下
            {
               conditions":后台查询参数
               Type:导出文件类型
               FileName:导出文件名
            }
* 返回值：  无
* 创建时间：2016-02-22
* 修改时间：2017-02-16
*/
    Export: function (options) {
        var param = { "FileName": options.filename, "Type": options.filetype, "conditions": options.conditions, action: "ExportExcelToDB"};
        $.download("../Excel/PostHandler.ashx", param, "post");
        //$.ExportXLS(param);
    },
    ExportAll: function (options) {
        var param = { "FileName": options.filename, "Type": options.filetype, "conditions": options.conditions, action: "ExportExcelAll"};
        $.download("../Excel/PostHandler.ashx", param, "post");
        //$.ExportXLS(param);
    },

    /*
    * 功能：    根据业务类型下载导入数据得模版文件
    * 参数：    options：
                {
                    type:业务类型, 取值参照 DownLoadHandler 枚举
                    FunctionCode:业务模块Code,
                    Ext:可导入文件类型,
                    ReturnDetailData:是否返回详细数据
                    after:function(){}//回调函数
                }
    * 返回值：  无
    * 创建时间：2016-08-22
    */
    ImportExcelTemplate: function (options) {
       // debugger;
        if ($.isPlainObject(options)) {
            var defaults = {
                ReturnDetailData: 0
            };

            var param = $.extend({}, defaults, options);

            if (param.type != "undefined") {
                if (!WebUploader.Uploader.support()) {
                    var error = "上传控件不支持您的浏览器！请尝试升级flash版本或者使用Chrome引擎的浏览器。<a target='_blank' href='http://www.chromeliulanqi.com'>下载页面</a>";
                    if (window.console) {
                        window.console.log(error);
                    }
                    return;
                }

				var UserID = JSON.parse(window.sessionStorage.getItem('login-info'));
		        if(!Y.checkNull(UserID))
		        	UserID = UserID.UserId;
		        param.UserID = UserID;

//              var id = "ImportExcelTemplate{0}".format(param.type);
				var id = typeof(param.filetype) == 'string' ? 
					"ImportExcelTemplate{0}".format(param.filetype) : 
					"ImportExcelTemplate{0}".format(param.filetype[0]);
                var modal = $("#" + id);
                $(modal).remove();
                var html =
                    '<div class="modal" id="{0}" data-backdrop="static">'.format(id) +
                        '<div class="modal-dialog">' +
                            '<div class="modal-content">' +
                                '<div class="modal-header">' +
                                    '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
                                    '<h4 class="modal-title">Excel导入</h4>' +
                                '</div>' +
                                '<div class="modal-body">' +
                                    '<div id="uploader" class="wu-example">' +
                                        '<p style="font-weight:bold;">导入说明:</p><p class="pt5">导入文件为EXCEL格式，请先下载模板进行必要信息填写，下载模板';

				console.log(param);
                if(typeof(param.filetype) == 'string'){
                	if(!Y.checkNull(param.state)){
                		html +=			'<a href="javascript:;" class="downTemplate">'+ param.filename +'</a></p>';
                	}else{
                		html +=			'<a href="javascript:;" onclick="$.DownloadExcelTemplate(\'{0}\')">{1}</a></p>'.format(param.filetype,param.filename);
//						html +=			'<a href="javascript:;" class="downTemplate">'+ param.filename +'</a></p>';
                	}
                }else{
                	param.filetype.map(function(item,i){
                		if(i > 0)
                			html += '、';
                			
                		if(!Y.checkNull(param.filename[i]['state'])){
                			html +=			'<a href="javascript:;" data-filetype="'+ param.filetype[i] +'" data-filename="'+ param.filename[i]['name'] +'" class="downTemplate">'+ param.filename[i]['name'] +'</a>';
                		}else{
                			html +=			'<a href="javascript:;" onclick="$.DownloadExcelTemplate(\''+ item +'\')">'+ param.filename[i]['name'] +'</a>';
//							html +=			'<a href="javascript:;" data-filetype="'+ param.filetype[i] +'" data-filename="'+ param.filename[i]['name'] +'" class="downTemplate">'+ param.filename[i]['name'] +'</a>';
                		}
                	})
                }
                    
                    html +=				'</p>' +
                                        '<div id="thelist" class="uploader-list"></div>' +
                                        '<div class="uploader-wrap clearfix pb20">' +
                                        '<input type="text" readonly class="form-control input-sm mr5 upload-file-name" style="width:300px; display:inline-block;" />' +
                                        '<div id="picker" style="display:inline-block;">选择文件</div>' +
                                        '<button id="ctlBtn" class="btn btn-white btn-sm btn-start-uploader ml5" style="display:none;">开始上传</button>' +
                                        '</div>' +
                                        '</div>' +
                                        ''+
//                                  '<a href="#" class="import-excel">点击上传</a>'+
                                    '</div></div></div></div>';
                $(html).appendTo("body");
                modal = $("#" + id);
//              var postData = { type: param.type, FunctionCode: param.FunctionCode, ReturnDetailData: param.ReturnDetailData };
//				$.param(postData)

				var postData = {}
				if(typeof(param.filetype) == 'string'){
				    postData = { filetype: param.filetype, action: param.action, UserID: param.UserID, MasterID: param.MasterID }; //cyl添加传入订货会内码ID参数:MasterID
				}
				
                $('.downTemplate').click(function () {
                   
				    if (typeof (param.filetype) == 'string') {				        
						$.Export(param);
					}else{
						var tempParam = {};
						tempParam.filename = $(this).data('filename');
						tempParam.filetype = $(this).data('filetype');
				        tempParam.conditions = param.conditions;
						$.Export(tempParam);
					}
				})

                var uploader = WebUploader.create({
                    swf: '../plugins/webuploader/Uploader.swf',
                    server: '/Excel/PostHandler.ashx',
                    formData: postData,
                    pick: '#picker',
                    accept: {
                        title: 'excel',
                        extensions: 'xls,xlsx',
                        mimeTypes: 'application/msexcel'
                    },
                    timeout: 0,
                    resize: false,
                    fileSingleSizeLimit: 10 * 1024 * 1024,//10M
                    duplicate: true
                });
				
				$('#picker').click(function(){
					$('.webuploader-element-invisible').removeAttr('multiple');
				})
				
				$("#ctlBtn").on('click', function () {
                    console.log("本次导入开始时间：" + new Date());
                	if(typeof(param.filetype) != 'string'){
                		var fname = $('.upload-file-name').val();
                		param.filename.map(function(item,i){
                			if(fname.indexOf(item.name) > -1){
                				uploader.options.formData = {filetype: param.filetype[i], action: param.action};
                			}
                		})
                	}
                    uploader.upload();
                });
                $('.import-excel').on('click',function() {
                    $.ImportExcelData({
                        type: "ShelfDisplay", after: function () {
                            //回调方法
                            //gridTask.reload();
                        }
                    });
                });

                // 当有文件被添加进队列的时候
                uploader.on('fileQueued', function (file) {
                    $("#thelist").html('<div id="' + file.id + '" class="item">' +
                        '<div class="state"></div>' +
                    '</div>');
//                  if(file.ext != 'xls'){
//              		$('#' + file.id).find('.state').append('<span class="label label-warning">导入文件后缀必须是.xls</span>');
//              		$(".upload-file-name").val('');
//                  	$(".btn-start-uploader").hide();
//              		return false;
//              	}
                    $(".upload-file-name").val(file.name);
                    $(".btn-start-uploader").show();
                });

                // 文件上传过程中创建进度条实时显示。
                uploader.on('uploadProgress', function (file, percentage) {
                    var $li = $('#' + file.id),
                        $percent = $li.find('.progress .progress-bar');

                    // 避免重复创建
                    if (!$percent.length) {
                        $percent = $('<div class="progress progress-striped active">' +
                          '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                          '</div>' +
                        '</div>').appendTo($li).find('.progress-bar');
                    }

                    $li.find('.state').text('上传中');

                    $percent.css('width', percentage * 90 + '%');
                    $(".upload-file-name").val("");
                    $(".btn-start-uploader").hide();
                });

                uploader.on('uploadSuccess', function (file, response) {
                	console.log(response);
                    if (response.IsSuccess) {
                        $('#' + file.id).find('.progress .progress-bar').css('width', 100 + '%');
                        if (Y.checkNull(response.Url)) {
                            $('#' + file.id) .find('.state').html('<span class="label label-success">' + response.Message + '</span>');
                        } else {
                            $('#' + file.id).find('.state').html('<span class="label label-warning" title="' + response.Message + '">' + response.Message + '</span>&nbsp;&nbsp;<a href="' + response.Url + '" target="_blank">下载错误数据</a>');
                        }
                        if ($.isFunction(param.after))
	                    	param.after(response, modal);
                    } else {
                        if (response.Message.indexOf("http://") >= 0 || response.Message.indexOf("ErrorExcel") >= 0) {
                            $('#' + file.id).find('.state').html("上传的数据中存在错误数据，请点击<a class='red' href='{0}' target='_blank'>下载错误数据</a>！".format(response.Message));
                        } else {
                            $('#' + file.id).find('.state').html('<span class="label label-danger" title="' + response.Message +'">' + response.Message + '</span>');
                        }
                    }

                });

                uploader.on('uploadError', function (file, response) {
                    console.log(response);
                    $('#' + file.id).find('.state').text('上传出错');
                });

                uploader.on('uploadComplete', function (file) {
                    $('#' + file.id).find('.progress').fadeOut(200);
                });

                modal.modal('show');
            }
        }
    }
});

/***************************************************** JS数据类型方法拓展   ********************************************************************************/
/*
* 功能：    拓展String类型方法，添加常用功能
* 创建时间：2015-11-18
*/
$.extend(String.prototype, {
    /*
    * 功能：    类似C# String.Format()格式化功能
    * 参数：    args：参数
    * 返回值：  无
    */
    format: function (args) {
        var result = this;
        if (arguments.length > 0) {
            if (arguments.length == 1 && typeof (args) == "object") {
                for (var key in args) {
                    if (args[key] != undefined) {
                        var reg = new RegExp("({" + key + "})", "g");
                        result = result.replace(reg, args[key]);
                    }
                }
            }
            else {
                for (var i = 0; i < arguments.length; i++) {
                    if (arguments[i] != undefined) {
                        //var reg = new RegExp("({[" + i + "]})", "g");//这个在索引大于9时会有问题
                        var reg = new RegExp("({)" + i + "(})", "g");
                        result = result.replace(reg, arguments[i]);
                    }
                }
            }
        }
        return result;
    }
});

/***************************************************** 控件拓展   ********************************************************************************/
